<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="searchInfo">
        <el-form-item label="">
          <el-input v-model="searchInfo.UserName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <warning-bar title="注：右上角头像下拉可切换角色" />
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDrawer('新增', null)">新增用户</el-button>
      </div>
      <el-table :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column align="left" label="序号" min-width="60" type="index"/>
        <el-table-column align="left" label="DID" min-width="150" prop="Did" />
        <el-table-column align="left" label="用户真实姓名" min-width="150" prop="UserName" />
        <el-table-column align="left" label="用户昵称" min-width="150" prop="NickName" />
        <el-table-column align="left" label="用户来源描述" min-width="180" prop="UserSource" />
        <el-table-column align="left" label="用户等级" min-width="180" prop="UserLevel" />
        <el-table-column align="left" label="手机号" min-width="180" prop="UserPhone" />
        <el-table-column align="left" label="用户来源类型" min-width="180" prop="UserSourceType" >
          <template #default="scope">
            <span>{{ userSourceTypeArr[scope.row.UserSourceType] }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="用户归属节点" min-width="180" prop="NodeId" />
        <el-table-column align="left" label="用户类别" min-width="180" prop="UserType"  >
          <template #default="scope">
            <span>{{ userTypeArr[scope.row.UserType] }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="用户状态" min-width="180" prop="UserStatus">
          <template #default="scope">
            <span>{{ formatStatus(scope.row.UserStatus) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="Files" @click="openDrawer('编辑', scope.row)">详情</el-button>
            <el-button type="danger" link icon="delete" @click="deleteUserFunc(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 查看详情抽屉 -->
    <el-drawer v-model="drawerVisible" size="60%" :before-close="closeDrawer" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ drawerTitle }}</span>
          <div>
            <el-button @click="closeDrawerFun">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </div>
        </div>
      </template>

      <el-form :model="userInfo" :rules="rules" ref="userForm" label-width="100px">
        <el-form-item label="用户真实姓名" prop="UserName">
          <el-input v-model="userInfo.UserName" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="userInfo.password" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="NickName">
          <el-input v-model="userInfo.NickName" />
        </el-form-item>
        <el-form-item label="手机号" prop="UserPhone">
          <el-input v-model="userInfo.UserPhone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfo.Email" />
        </el-form-item>
        <el-form-item label="用户来源类型" prop="UserSourceType" disabled>
          <el-select v-model="userInfo.UserSourceType" placeholder="请选择用户来源类型">
            <el-option label="超级节点" :value=0 />
            <el-option label="平台注册" :value=1 />
            <el-option label="业务应用" :value=2 />
          </el-select>
        </el-form-item>
        <el-form-item label="用户来源描述">
        <el-input v-model="userInfo.UserSource" />
      </el-form-item>
        <el-form-item label="用户类别" prop="UserType" disabled>
          <el-select v-model="userInfo.UserType" placeholder="请选择用户类别">
            <el-option label="个人" :value=0 />
            <el-option label="企业" :value=1 />
            <el-option label="政府部门" :value=2 />
          </el-select>
        </el-form-item>
      </el-form>
    </el-drawer>

    <el-drawer v-model="visible" size="60%" :before-close="closeUserDetailDialog" :show-close="false">
      <template #header>
        <span class="text-lg">用户详情</span>
      </template>
      <el-form :model="userDetail" label-width="100px">
        <!-- 详情展示，修改为可编辑 -->
        <el-form-item label="DID">
          <el-input v-model="userDetail.Did" disabled />
        </el-form-item>
        <el-form-item label="用户真实姓名" prop="UserName">
          <el-input v-model="userDetail.UserName" />
        </el-form-item>


        <el-form-item label="用户昵称">
          <el-input v-model="userDetail.NickName" disabled/>
        </el-form-item>
        <el-form-item label="用户来源描述">
          <el-input v-model="userDetail.UserSource" />
        </el-form-item>

        <el-form-item label="用户等级">
          <el-input v-model="userDetail.UserLevel" disabled/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userDetail.UserPhone" disabled/>
        </el-form-item>
        <el-form-item label="用户来源类型" prop="UserSourceType" disabled>
          <el-select v-model="userInfo.UserSourceType" placeholder="请选择用户来源类型">
            <el-option label="超级节点" value="1" />
            <el-option label="平台注册" value="2" />
            <el-option label="业务应用" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户归属节点">
          <el-input v-model="userDetail.NodeId" disabled/>
        </el-form-item>
        <el-form-item label="用户类别" prop="UserType" disabled>
          <el-select v-model="userInfo.UserType" placeholder="请选择用户类别">
            <el-option label="个人" value="个人" />
            <el-option label="企业" value="企业" />
            <el-option label="政府部门" value="政府部门" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态" disabled>
          <el-select v-model="userDetail.UserStatus" placeholder="请选择用户状态">
            <el-option
                v-for="option in statusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>



      </el-form>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="updateUser">保存</el-button>
          <el-button @click="closeUserDetailDialog">关闭</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getlistUser, addNWYLUser, deleteNWYLUser, updateNWYLUserStatus,updateNWYLUser } from '@/api/userControl'

const searchInfo = reactive({ UserName: '' })

const page = ref()
const total = ref(0)
const pageSize = ref(10) // 每页条数

const tableData = ref([])
const drawerTitle = ref('')
const drawerVisible = ref(false)
const visible = ref(false)
const userInfo = ref({
  UserName: '',
  password: '',
  NickName: '',
  UserPhone: '',
  UserSource:'',
  UserSourceType:'',
  UserType:'',
  Email: '',
  authorityId: '',
  authorityIds: [],
  enable: 1,
})
const userSourceTypeArr=ref(['超级节点','平台注册','业务应用','无'])
const userTypeArr=ref(['个人','企业','政府部门','无'])
const userDetail = ref({})
const rules = ref({
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }],
  nickName: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入合法手机号', trigger: 'blur' }],
  email: [{ pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱', trigger: 'blur' }],
  authorityId: [{ required: true, message: '请选择用户角色', trigger: 'blur' }],
})
const statusOptions = ref([
  { label: '启用', value: 1 },
  { label: '停止', value: 2 }
])

const formatStatus = (status) => {
  const statusOption = statusOptions.value.find(option => option.value === status)
  return statusOption ? statusOption.label : ''
}

// 搜索按钮点击事件
const onSubmit = async () => {
  try {
    await getTableData();
  } catch (error) {
    console.error('Search error:', error);
  }
}

// 重置按钮点击事件
const onReset = () => {
  searchInfo.UserName = ''
  tableData.value = []
  total.value = 0
  page.value = 1 // 重置分页到第1页
}

// 打开抽屉
const openDrawer = (title, row) => {
  drawerTitle.value = title === '新增' ? '新增用户' : '查看详情'
  if (row) {
    userDetail.value = row
    visible.value = true
  } else {
    userInfo.value = {
      UserName: '',
      password: '',
      NickName: '',
      UserPhone: '',
      Email: '',
      UserSource:'',
      UserSourceType:'',
      UserType:'',
      authorityId: '',
      authorityIds: [],
      enable: 1,
    }
    drawerVisible.value = true
  }
}

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false
}

// 提交表单
const submitForm = async () => {
  try {
    userInfo.value.authorityId = 111
    userInfo.value.authorityIds[0] = userInfo.value.authorityId
    const req = { ...userInfo.value }
    await addNWYLUser(req)
    ElMessage.success('用户新增成功')
    drawerVisible.value = false
    await getTableData() // 刷新表格数据
  } catch (error) {
    console.error('新增用户失败', error)
    ElMessage.error('新增用户失败')
  }
}

// 更新用户信息
const updateUser = async () => {
  try {
    await updateNWYLUserStatus({ "UserId": userDetail.value.ID, "Status": Number(userDetail.value.UserStatus) })
    await updateNWYLUser({ "UserId": userDetail.value.ID,"UserName": userDetail.value.UserName ,"UserSource": userDetail.value.UserSource})
    ElMessage.success('用户信息更新成功')
    closeUserDetailDialog()
    await getTableData() // 刷新表格数据
  } catch (error) {
    console.error('更新用户信息失败', error)
    ElMessage.error('更新用户信息失败')
  }
}

// 删除按钮点击事件
const deleteUserFunc = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗?', '删除确认', {
      type: 'warning'
    })
    await deleteNWYLUser({ "id": row.ID })
    ElMessage.success('用户删除成功')
    await getTableData() // 刷新表格数据
  } catch (error) {
    // 取消删除操作或失败
  }
}

// 获取表格数据
const getTableData = async () => {
  try {
    const response = await getlistUser(page.value, pageSize.value);
    console.log('Response:', response); // 输出完整响应数据
    if (response.code === 0) {
      const data = response.data;
      tableData.value = data.userList || [];
      total.value = data.totalNum;
      page.value=data.pageNum;
      console.log('TableData:', tableData.value);
      console.log('Total:', total.value);
      console.log('Current Page:', page.value);
    } else {
      ElMessage.error(response.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('API Error:', error);
    ElMessage.error('获取数据失败');
  }
}




const handleSizeChange = (val) => {
  pageSize.value = val
  page.value = 1 // 每次改变每页条数时，回到第一页
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData() // 切换页码时重新获取数据
}


const closeUserDetailDialog = () => {
  visible.value = false
}
const closeDrawerFun = () => {
  drawerVisible.value = false
}

onMounted(() => {
  getTableData() // 获取初始数据
})

</script>


<style scoped lang="scss">
.warning {
  color: #dc143c;
}
</style>
